package ldkxingzhe.l365calendar.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;

import ldkxingzhe.l365calendar.model.ScheduleAlarmEntity;

/**
 * schedule_alarm表的dao层
 * Created by ke on 16-2-10.
 */
public class AlarmDao {

    private L365CalendarOpenHelper helper;
    public AlarmDao(Context context){
        helper = L365CalendarOpenHelper.getInstance(context);
    }

    public int insert(@NonNull ScheduleAlarmEntity entity){
        return (int) helper.getWritableDatabase()
                .insert(L365CalendarOpenHelper.TABLE_SCHEDULE_ALARM, null,
                        generateContentValue(entity));
    }

    private ContentValues generateContentValue(ScheduleAlarmEntity entity) {
        ContentValues resultContentValues = new ContentValues();
        resultContentValues.put(L365CalendarOpenHelper.CREATED, entity.getCreated());
        resultContentValues.put(L365CalendarOpenHelper.MODIFIED, entity.getModified());
        resultContentValues.put(L365CalendarOpenHelper.SCHEDULE_ALARM_BEFORE_TIME, entity.getBeforeTime());
        resultContentValues.put(L365CalendarOpenHelper.SCHEDULE_ALARM_SCHEDULE_ID, entity.getScheduleId());
        resultContentValues.put(L365CalendarOpenHelper.SCHEDULE_ALARM_NEXT_ALARM, entity.getNextAlarm());
        return resultContentValues;
    }

    ScheduleAlarmEntity getAlarmEntity(@NonNull Cursor cursor){
        ScheduleAlarmEntity resultEntity = new ScheduleAlarmEntity();
        resultEntity.set_id(cursor.getInt(cursor.getColumnIndex(L365CalendarOpenHelper.ID)));
        resultEntity.setCreated(cursor.getLong(cursor.getColumnIndex(L365CalendarOpenHelper.CREATED)));
        resultEntity.setModified(cursor.getLong(cursor.getColumnIndex(L365CalendarOpenHelper.MODIFIED)));
        resultEntity.setBeforeTime(cursor.getLong(cursor.getColumnIndex(L365CalendarOpenHelper.SCHEDULE_ALARM_BEFORE_TIME)));
        resultEntity.setScheduleId(cursor.getInt(cursor.getColumnIndex(L365CalendarOpenHelper.SCHEDULE_ALARM_SCHEDULE_ID)));
        resultEntity.setNextAlarm(cursor.getLong(cursor.getColumnIndex(L365CalendarOpenHelper.SCHEDULE_ALARM_NEXT_ALARM)));
        return resultEntity;
    }

    Cursor selectAll(){
        return helper.getReadableDatabase()
                .rawQuery("SELECT * FROM " + L365CalendarOpenHelper.TABLE_SCHEDULE_ALARM, null);
    }
}
